package com.dillon.acr.ui.home


import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.graphics.Typeface
import android.util.DisplayMetrics
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.jzvd.Jzvd
import com.afollestad.materialdialogs.MaterialDialog
import com.blankj.utilcode.util.*
import com.dillon.acr.R
import com.dillon.acr.base.App
import com.dillon.acr.base.App.Companion.needRefresh
import com.dillon.acr.base.BAct
import com.dillon.acr.bean.MediaInfo
import com.dillon.acr.bean.UserInfo
import com.dillon.acr.key.ActionK
import com.dillon.acr.key.CacheK
import com.dillon.acr.key.CommonK
import com.dillon.acr.services.task.RecorderSer
import com.dillon.acr.ui.setting.SettingAct
import com.dillon.acr.utils.AUtils
import com.dillon.acr.utils.LocalCacheUtils
import com.dillon.acr.utils.MediaPopup
import com.dillon.acr.utils.view.shimmer.Shimmer
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.yanzhenjie.recyclerview.OnItemClickListener
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.layout_common_title.*


class HomeAct : BAct(), View.OnClickListener, OnItemClickListener, HomeAdapter.ItemManagerListener,
    SwipeRecyclerView.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    private var materialDialog: MaterialDialog? = null

    private var selectType: String = CommonK.Type_Media_Audio
    private var mAdapter: HomeAdapter? = null
    private var mediaInfoListByPage: MutableList<MediaInfo>? = null
    private var mediaInfoListBySelectType: MutableList<MediaInfo>? = null

    private var pageNum = 1//当前页数
    private var pageSize = 10//分页数量

    private var chooseMediaInfo: MediaInfo? = null
    private var actionType: String? = null

    override fun initUi() {
        super.initUi()
        setContentView(R.layout.activity_home)
    }

    override fun initView() {
        super.initView()
        Jzvd.FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        Jzvd.NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        if (null == LocalCacheUtils.getLocalUser()) {
            val localUser = UserInfo()
            localUser.deviceId = DeviceUtils.getUniqueDeviceId()
            LocalCacheUtils.saveLocalUser(localUser)
            AUtils.simpleLog("APP_FIRST_START")

            val title = getString(R.string.welcome)
            val mMessage = getString(R.string.how_to_use)
            materialDialog?.cancel()
            materialDialog = MaterialDialog(this)
                .title(text = title)
                .icon(R.mipmap.ic_logo)
                .message(text = mMessage)
                .cornerRadius(res = R.dimen.dp_20)
                .positiveButton(null, getString(R.string.check)) {
                    goSettingAct()
                }
            materialDialog?.setOnDismissListener { needRefresh = false }
            if (materialDialog != null && !materialDialog!!.isShowing) {
                materialDialog?.show()
            }
        }
        iv_title_right.setImageResource(R.drawable.icon_setting)
        lay_title_right.visibility = View.VISIBLE
        tv_title_left.text = AppUtils.getAppName().toString()
        // iv_title_left.setImageResource(R.mipmap.ic_logo)
        sw_ac.isChecked = App.acOpen
        sw_ac.text = if (App.acOpen) {
            getString(R.string.on)
        } else {
            getString(R.string.off)
        }
        sw_ac.setOnCheckedChangeListener { _, checked ->
            if (checked) {
                App.acOpen = true
                ToastUtils.showShort(resources.getString(R.string.ac_open))
                SPUtils.getInstance().put(CacheK.acOpen, true)
                sw_ac.text = getString(R.string.on)
            } else {
                App.acOpen = false
                SPUtils.getInstance().put(CacheK.acOpen, false)
                sw_ac.text = getString(R.string.off)
            }
        }

        val pool = RecyclerView.RecycledViewPool()
        pool.setMaxRecycledViews(0, 10)
        recyclerView.setRecycledViewPool(pool)
        recyclerView.itemAnimator?.changeDuration = 0
        (recyclerView.itemAnimator as SimpleItemAnimator?)!!.supportsChangeAnimations = false

        recyclerView.setLoadMoreListener(this)
        refreshLayout.setOnRefreshListener(this)
        recyclerView.setOnItemClickListener(this)
        recyclerView?.layoutManager = GridLayoutManager(this, 1)
        mAdapter = HomeAdapter(this, this)
        recyclerView?.adapter = mAdapter
    }

    override fun initListener() {
        super.initListener()
        iv_title_right.setOnClickListener(this)
        //    lay_title_left.setOnClickListener(this)
        iv_recording.setOnClickListener {
            when {
                App.capturingAudio -> {
                    App.capturingAudio = false
                    AUtils.startCommonService(RecorderSer::class.java)
                }
                else -> {
                    LogUtils.d("Not recording")
                }
            }
        }
    }

    override fun onClick(view: View?) {
        when (view) {
            lay_title_left -> {
                val mTitle = AppUtils.getAppName() + "  v" + AppUtils.getAppVersionName()
                val mMessage = resources.getString(R.string.app_des)
                materialDialog?.cancel()
                materialDialog = MaterialDialog(this)
                    .icon(R.mipmap.ic_logo)
                    .title(text = mTitle)
                    .message(text = mMessage)
                    .cornerRadius(res = R.dimen.dp_20)
                materialDialog?.setOnDismissListener { needRefresh = false }
                if (materialDialog != null && !materialDialog!!.isShowing) {
                    materialDialog?.show()
                }

            }
            iv_title_right -> {
                goSettingAct()
            }

        }
    }

    private fun refreshData(selectType: String) {
        pageNum = 1
        refreshLayout.isRefreshing = false
        mediaInfoListBySelectType = AUtils.getMediaInfoListByType(selectType)
        //第一页数据
        mediaInfoListByPage =
            AUtils.getMediaInfoListByPage(mediaInfoListBySelectType, pageSize, pageNum)
        if (mediaInfoListByPage.isNullOrEmpty()) {
            tv_empty.visibility = View.VISIBLE
            recyclerView.loadMoreFinish(true, false)
        } else {
            tv_empty.visibility = View.INVISIBLE
            recyclerView.loadMoreFinish(false, true)
        }
        mAdapter?.notifyDataSetChanged(mediaInfoListByPage)

        //   mAdapter?.seeOnlyLove(mediaInfoListByPage)

    }

    override fun onBackPressed() {
        if (Jzvd.backPress()) {
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        LogUtils.i("onPause")
        if (materialDialog != null && materialDialog!!.isShowing) {
            materialDialog?.cancel()
        }
        Jzvd.releaseAllVideos()
    }

    override fun onResume() {
        super.onResume()
        LogUtils.i("onResume")
        if (needRefresh) {
            refreshData(selectType)
        } else {
            needRefresh = true
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        materialDialog?.cancel()
    }

    override fun onLoadMore() {
        pageNum++
        val tempMediaInfoList =
            AUtils.getMediaInfoListByPage(mediaInfoListBySelectType, pageSize, pageNum)
        if (tempMediaInfoList.isNullOrEmpty()) {
            recyclerView!!.loadMoreFinish(true, false)
            LogUtils.d("noMore", "page$pageNum")
        } else {
            recyclerView.postDelayed({
                mediaInfoListByPage?.addAll(tempMediaInfoList)
                mAdapter?.notifyItemRangeInserted(
                    mediaInfoListByPage!!.size - tempMediaInfoList.size,
                    tempMediaInfoList.size
                )
            }, 500) //  延时运行

            val listSize = tempMediaInfoList.size
            if (listSize < pageSize) {
                //一页加载完
                recyclerView.loadMoreFinish(true, false)
                LogUtils.d("In one page", "Page$pageNum", "Size$listSize")
            } else {
                //可能有下一页
                recyclerView.loadMoreFinish(false, true)
                LogUtils.d("More than one page", "Page$pageNum", "Size$listSize")
            }
            ToastUtils.showShort(getString(R.string.loading_more))
        }
    }

    override fun onRefresh() {
        refreshData(selectType)
    }

    override fun onItemClick(view: View?, adapterPosition: Int) {
        val mediaInfo = mediaInfoListBySelectType?.get(adapterPosition)
        if (mediaInfo != null) {
            XPopup.Builder(this)
                .popupAnimation(PopupAnimation.TranslateAlphaFromLeft)
                .isDestroyOnDismiss(true)
                .asCustom(MediaPopup(this, mediaInfo))
                .show()
        }
    }

    override fun love(mediaInfo: MediaInfo, position: Int) {
        val fileName = mediaInfo.file!!.name
        val loved = SPUtils.getInstance().getBoolean(fileName, false)
        if (loved) {
            SPUtils.getInstance().put(fileName, false)
        } else {
            SPUtils.getInstance().put(fileName, true)
        }
        mAdapter?.notifyItemChanged(position)
    }

    override fun share(mediaInfo: MediaInfo, position: Int) {
        AUtils.shareMediaFile(this@HomeAct, mediaInfo)

    }

    override fun save(mediaInfo: MediaInfo, position: Int) {
        AUtils.saveMediaExternal(this@HomeAct, mediaInfo)
    }

    override fun delete(mediaInfo: MediaInfo, position: Int) {

        val mTitle = getString(R.string.dialog_common_title)
        val mMessage = getString(R.string.delete) + " " + mediaInfo.title
        materialDialog?.cancel()
        materialDialog = MaterialDialog(this)
            //.icon(R.mipmap.ic_launcher)
            .title(text = mTitle)
            .message(text = mMessage)
            .cornerRadius(res = R.dimen.dp_20)
            .negativeButton(null, getString(R.string.delete)) {
                val flag = FileUtils.delete(mediaInfo.file)
                if (flag) {
                    SPUtils.getInstance().remove(mediaInfo.file!!.name)
                    recyclerView.postDelayed({
                        LogUtils.d("position:$position")
                        mediaInfoListByPage?.removeAt(position)
                        mediaInfoListBySelectType?.removeAt(position)
                        mAdapter?.notifyItemRemoved(position)
                        mAdapter?.notifyItemRangeChanged(position, mediaInfoListByPage!!.size)
                        if (mediaInfoListByPage.isNullOrEmpty()) {
                            refreshData(selectType)
                        }

                    }, 500) //  延时运行
                } else {
                    ToastUtils.showShort(getString(R.string.failed))
                }

                if (mediaInfoListBySelectType != null && mediaInfoListBySelectType!!.isEmpty()) {
                    tv_empty.visibility = View.VISIBLE
                }

            }
            .positiveButton(null, getString(R.string.cancel)) {
            }
        materialDialog?.setOnDismissListener { needRefresh = false }
        if (materialDialog != null && !materialDialog!!.isShowing) {
            materialDialog?.show()
        }

    }

    private fun goSettingAct() {
        ActivityUtils.startActivity(SettingAct::class.java)

    }

}
